package com.ruix.app.ui.user;

import android.content.Intent;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.NetUtils;
import com.ruix.app.R;
import com.ruix.app.manager.UserManager;
import com.ruix.app.model.User;
import com.ruix.app.model.WXUserInfo;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.CountDownTimerUtil;
import com.ruix.app.util.RegUtil;
import com.ruix.app.util.SoftInputUtil;

import org.json.JSONObject;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/12.
 */

public class BindPhoneActivity extends BaseActivity implements View.OnClickListener {


    private Button sendVerifyView;
    private EditText phoneNumberEditText, verifyCodeEditText;
    private CountDownTimerUtil countDownTimerUtil;
    private int REQUST_CODE_IMPORT = 321;
    private WXUserInfo wxUserInfo;

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_bind_phone;
    }

    @Override
    protected void initView() {
        sendVerifyView = (Button) findViewById(R.id.btn_send_verify);
//        sendVerifyView
        phoneNumberEditText = (EditText) findViewById(R.id.et_phone_num);
        verifyCodeEditText = (EditText) findViewById(R.id.et_verify_code);

        addLayoutListener(findViewById(R.id.root_layout),findViewById(R.id.btn_bind_phone));
    }


    @Override
    protected void initLocalData() {
        Intent intent = getIntent();
        if (intent != null) {
            wxUserInfo = (WXUserInfo) intent.getSerializableExtra("wxuserinfo");
        }

    }

    @Override
    protected void initListener() {
        sendVerifyView.setOnClickListener(this);
        findViewById(R.id.close_page).setOnClickListener(this);
        findViewById(R.id.btn_bind_phone).setOnClickListener(this);

        phoneNumberEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        verifyCodeEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
        phoneNumberEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String value = s.toString().trim();
                if (value.length() > 11) {
                    phoneNumberEditText.setBackgroundResource(R.drawable.shape_regist_edit_red_bg);
                } else {
                    phoneNumberEditText.setBackgroundResource(R.drawable.shape_regist_edit_bg);
                }

            }
        });
        verifyCodeEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    SoftInputUtil.hideSoftInput(verifyCodeEditText);
                    bindPhoneNume();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    // 设置状态栏颜色
    protected int statusBarTintColor() {
        return R.color.white;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_page:
                finish(); //TODO
//
                break;

            case R.id.btn_send_verify:
                sendVerifyCode();
                break;

            case R.id.btn_bind_phone:
                bindPhoneNume();
                break;

        }
    }

    private void startCountdownVerifyTime(long millisInFuture) {
        if (countDownTimerUtil != null) {
            countDownTimerUtil.cancel();
            countDownTimerUtil.onFinish();
        }
        setVerifyViewToCountdownStatus();
        countDownTimerUtil = new CountDownTimerUtil(new CountDownTimerUtil.ICountDownTimerInterface() {
            @Override
            public void countDownTimerFinish() {
                resetSendVerifyView();
            }
        }, new CountDownTimerUtil.ICountDownTimerUpdate() {
            @Override
            public void setText(String text) {
                sendVerifyView.setText(text);
            }
        }, null, millisInFuture, 1000);
        countDownTimerUtil.start();
    }

    private void stopCountDown() {
        if (countDownTimerUtil != null) {
            countDownTimerUtil.cancel();
            countDownTimerUtil.onFinish();
            countDownTimerUtil = null;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopCountDown();
    }

    private void setVerifyViewToCountdownStatus() {
        sendVerifyView.setEnabled(false);
        sendVerifyView.setTextColor(getResources().getColor(R.color.gray));
        sendVerifyView.setBackgroundResource(R.drawable.shape_regist_edit_bg);
    }


    private void resetSendVerifyView() {
        sendVerifyView.setEnabled(true);
        sendVerifyView.setText("重新发送");
        sendVerifyView.setTextColor(getResources().getColor(R.color.green));
        sendVerifyView.setBackgroundResource(R.drawable.shape_gree_corner_bg);
    }

    //发送验证码
    private void sendVerifyCode() {
        String phoneNumber = phoneNumberEditText.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)
                || "".equals(phoneNumber)) {
            showErrorTip("请输入正确的手机号");
            return;
        }

        if (!RegUtil.checkPhone(phoneNumber)) {
            showErrorTip("请输入正确的手机号");
            return;
        }

        showLoading();
        RequestFactory.sendVerify(phoneNumber, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                startCountdownVerifyTime(60000);
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });

    }

    public void bindPhoneNume() {
        String phoneNumber = phoneNumberEditText.getText().toString().trim();
        String varifiCode = verifyCodeEditText.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)
                || "".equals(phoneNumber)) {
            showErrorTip("请输入手机号");
            return;
        }

        if (TextUtils.isEmpty(varifiCode)
                || "".equals(varifiCode)
                || varifiCode.length() < 2) {
            showErrorTip("请输入验证码");
            return;
        }

        if (!RegUtil.checkPhone(phoneNumber)) {
            showErrorTip("请输入正确的手机号");
            return;
        }

        showLoading();
        RequestFactory.bindMobile(phoneNumber, varifiCode, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                if (value != null) {
                    JSONObject data = value.optJSONObject("data");
                    if (data != null) {
                        JSONObject userObject = data.optJSONObject("user");
                        User user = new User().parse(userObject);
                        UserManager.sharedInstance().setCurrentUser(user);
                        UserManager.sharedInstance().registHuanXin();
                    }
                }
                importUserInfo();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });


    }

    public void importUserInfo() {
        Intent intent = new Intent(this, ImportUserInfoActivity.class);
        intent.putExtra("wxuserinfo", wxUserInfo);
        startActivityForResult(intent, REQUST_CODE_IMPORT);
//        this.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUST_CODE_IMPORT) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
            }
            finish();
        }
    }

    public void registEMC(String num) {
        try {
            //同步
            EMClient.getInstance().createAccount(num + "ruix", "121");

        } catch (HyphenateException e) {
            e.printStackTrace();
        }

    }

    public void loginEMC() {
        //异步
        EMClient.getInstance().login("", "", new EMCallBack() {

            @Override
            public void onSuccess() {
                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().groupManager().loadAllGroups();
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    public void addConnection() {
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());
    }


    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {

        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                    } else {
                        if (NetUtils.hasNetwork(BindPhoneActivity.this)) {
                            //连接不到聊天服务器
                        } else {

                        }
                        //当前网络不可用，请检查网络设置
                    }
                }
            });
        }
    }

    /**
     * @param rootView 根布局
     * @param bottomView 需要显示的最下方View，
     */
    public void addLayoutListener(final View rootView, final View bottomView) {
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                rootView.getWindowVisibleDisplayFrame(rect);//获取rootView的可视区域
                int invisibleHeight = rootView.getRootView().getHeight() - rect.bottom;//获取rootView的不可视区域高度
                if (invisibleHeight > 150) { //键盘显示
                    int[] location = new int[2];
                    bottomView.getLocationInWindow(location); //获取bottomView的坐标
                    int scrollHeight = (location[1] + bottomView.getHeight()) - rect.bottom;//算出需要滚动的高度
                    if (scrollHeight != 0) {//防止界面元素改变调用监听，使界面上下跳动，如验证码倒计时
                        rootView.scrollTo(0, scrollHeight);
                    }
                } else {
                    rootView.scrollTo(0, 0);
                }
            }
        });
    }


}
